package com.huawei.app.demo.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.huawei.app.demo.AppConstants;
import com.huawei.app.demo.R;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.demo.util.SoundUtils;

import java.util.Objects;

/**
 * 音频
 *
 * @since 2021-01-20
 */
public class AudioFragment extends CustomFragment {

    private static final String TAG = AudioFragment.class.getSimpleName();
    private Context context;
    private View rootView;
    private TextView volume;
    private SoundUtils soundhelper = new SoundUtils();
    private AudioManager audioManager = null;
    private int fourpercent;

    @Override
    public String getTitle() {
        return "音频";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_audio, container, false);

        //init view
        audioManager = (AudioManager) Objects.requireNonNull(getContext()).getSystemService(Context.AUDIO_SERVICE);
        rootView.findViewById(R.id.volume);
        volume = rootView.findViewById(R.id.current_volume);
        volume.setText(refresh(audioManager)+"%");
        Button openMicrophone = rootView.findViewById(R.id.btn_open_microphone);
        Button stopMicrophone = rootView.findViewById(R.id.btn_stop_microphone);
        Button play = rootView.findViewById(R.id.btn_player);
        Button volumeUp = rootView.findViewById(R.id.btn_volume_up);
        Button volumeDown = rootView.findViewById(R.id.btn_volume_down);



        //init event
        openMicrophone.setOnClickListener(this);
        stopMicrophone.setOnClickListener(this);
        play.setOnClickListener(this);
        volumeUp.setOnClickListener(this);
        volumeDown.setOnClickListener(this);

        return rootView;
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        if(soundhelper!= null){
            soundhelper = null;
        }
    }


    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_open_microphone: {
                openMicrophone();
                break;
            }
            case R.id.btn_stop_microphone: {
                stopMicrophone();
                break;
            }
            case R.id.btn_player: {
                playing();
                break;
            }
            case R.id.btn_volume_up: {
                turnupVolume();
                break;
            }
            case R.id.btn_volume_down: {
                turndownVolume();
                break;
            }
            default:
                break;
        }
    }

    private void openMicrophone(){
        if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 0);
        }else {
            soundhelper.startRecording();
        }
    }

    private void stopMicrophone(){
        soundhelper.stopRecording();
    }

    private void playing(){
        if(soundhelper.isAudioFileexist()) {
            soundhelper.startPlay(soundhelper.getAudioFile());
        }else{
            Toast.makeText(getActivity(),"请先录音",Toast.LENGTH_LONG).show();
        }
    }

    private void turnupVolume(){
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)+fourpercent,AudioManager.FLAG_PLAY_SOUND);
        volume.setText(refresh(audioManager)+"%");
        Log.d(TAG, "onClick:volume_up,max volume is "+audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)+" current volume is "+audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
    }

    private void turndownVolume(){
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)-fourpercent,AudioManager.FLAG_PLAY_SOUND);
        volume.setText(refresh(audioManager)+"%");
        Log.d(TAG, "onClick:volume_down,max volume is "+audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)+" current volume is "+audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
    }

    /**
     * 改变音量后，刷新当前音量大小显示
     * @param audioManager
     * @return
     */
    private String refresh(AudioManager audioManager){
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        fourpercent = maxVolume/25;
        int percent = currentVolume*100/maxVolume;
        return String.valueOf(percent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        if(requestCode == 0 ){
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                soundhelper.startRecording();
            }
        }
    }

}
